/**
 * Created by I_am_young on 2016/1/23.
 */
var gulp = require('gulp'), //gulp
    sass = require('gulp-ruby-sass'), //sass处理
    autoprefixer = require('gulp-autoprefixer'), //css添加前缀 -webkit这些
    imageMin = require('gulp-imagemin'), //图片压缩
    minifyCss = require('gulp-minify-css'), //压缩css
    htmlMin = require('gulp-htmlmin'), //html压缩
    processhtml = require('gulp-processhtml'), //html处理
    uglify = require('gulp-uglify'), //丑化代码
    clean = require('gulp-clean'), //清除文件
    cache = require('gulp-cache'), //缓存
    browserSync = require('browser-sync'), //修改与客户端同步
    reload = browserSync.reload, //重置函数
    notify = require('gulp-notify'); //控制台打印信息,并出现错误是提示错误，防止watch停止

var
    _SRC_ = "src/",
    _DIST_ = "dist/";

var config = {
    scriptUrl: _SRC_ + '**/*.js',
    htmlUrl: _SRC_ + '**/*.html',
    cssUrl: _SRC_ + 'css/*.scss',
    imageUrl: _SRC_ + 'img/**/*'
};

gulp.task('html', function () {
    return gulp.src(config.htmlUrl, {base: "src"})
        .pipe(processhtml())
        .pipe(gulp.dest(_DIST_))
        .pipe(reload({stream: true}));
        //.pipe(notify({
        //    message: 'html task complete'
        //}));
});

//部署样式
gulp.task('sass', function () {
    return sass(config.cssUrl, {style: 'expanded', base: "src"})
        //.pipe(minifyCss())
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8',
            'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(gulp.dest(_DIST_))
        .pipe(reload({stream: true}));
        //.pipe(notify({
        //    message: 'sass task complete'
        //}));
});

//部署脚本
gulp.task('js', function () {
    return gulp.src(config.scriptUrl, {base: "src"})
        //.pipe(uglify())
        .pipe(gulp.dest(_DIST_))
        .pipe(reload({stream: true}));
        //.pipe(notify({
        //    message: 'js task complete'
        //}));
});

//压缩图片
gulp.task('img', function () {
    return gulp.src(config.imageUrl, {base: "src"})
        //质量为 3
        .pipe(cache(imageMin({optimizationLevel: 3, progressive: true, interlaced: true})))
        .pipe(gulp.dest(_DIST_))
        .pipe(reload({stream: true}));
        //.pipe(notify({
        //    message: 'img task complete'
        //}));
});

//清除部署目录
gulp.task('clean', function () {
    return gulp.src([_DIST_], {read: true}).pipe(clean());
});

//默认操作
gulp.task('default', ['clean'], function () {
    gulp.start('html', 'sass', 'js', 'img');
});

// 看手
gulp.task('watch', function () {
    browserSync({
        server: {
            baseDir: 'dist'
        }
        //local:'localhost',
        //host:'localhost',
        //port:3000
    });

    // 看守所有.scss档
    gulp.watch(_SRC_+'/**/*.scss', ['sass']);

    // 看守所有.js档
    gulp.watch(config.scriptUrl, ['js']);

    // 看守所有图片档
    gulp.watch(config.imageUrl, ['img']);

    // 看守所以html
    gulp.watch(config.htmlUrl, ['html']);

});